package com.ruoyi.framework.websocket;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.Semaphore;
import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.OffLineMsg;
import com.ruoyi.system.service.IOffLineMsgService;
import com.ruoyi.system.service.ISysNoticeService;
import com.ruoyi.system.service.ISysUserService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.context.ApplicationContext;

/**
 * websocket 消息处理
 *
 * @author wlq
 */
@Component
@ServerEndpoint("/websocket")
public class WebSocketServer
{
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    // 用于存储用户ID和对应的WebSocket session
    private static final HashMap<String, Session> sessions = new HashMap<>();

    /**
     * 用来解决webSocket中无法注入mapper
     */
    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketServer.applicationContext = applicationContext;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws Exception
    {
        // 获取URL中的参数
        Map<String, List<String>> params = session.getRequestParameterMap();
        List<String> funcTypes = params.get("userid");
        if (!funcTypes.isEmpty()) {
            // 取出funcType参数的值
            String userId = funcTypes.get(0);
            sessions.put(userId, session);
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session)
    {
        // 获取URL中的参数
        Map<String, List<String>> params = session.getRequestParameterMap();
        List<String> funcTypes = params.get("userid");
        if (!funcTypes.isEmpty()) {
            // 取出funcType参数的值
            String userId = funcTypes.get(0);
            sessions.remove(userId);
        }
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception
    {

    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session)
    {
        try {
            AjaxResult msg = JSON.parseObject(message, AjaxResult.class);

            //0:心跳包
            if("heartbeat".equals(msg.get("data").toString())){
                WebSocketUsers.putUserId(session.getId(), Long.parseLong(msg.get("msg").toString()));
            }
            //聊天消息
            else if ("chat".equals(msg.get("data").toString())) {
                msg.put("data","chat");
                String json = JSON.toJSONString(msg);
                onLineBroadcast(json);
            }
            else if ("public".equals(msg.get("data").toString())) {//公告
                msg.put("data","public");
                String json = JSON.toJSONString(msg);
                allUserMessage(json,session);
            }
            else if ("person".equals(msg.get("data").toString())) {//指定人的通知
                String userid = Convert.toStr(msg.get("code"));
                String json = JSON.toJSONString(msg);
                sendMessageToUser(userid,json);
            }
            else{
                onLineBroadcast(message);
            }
        }
        catch (Exception ex){

        }
    }

    // 发送消息给指定的用户
    public void sendMessageToUser(String userId, String message) {
        Session session = sessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                // 处理发送消息时的异常
            }
        }
    }

    public void onLineBroadcast(String message)  {
        for (Session session : sessions.values())
        {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                // 处理发送消息时的异常
            }
        }
    }

    public void allUserMessage(String message, Session cursession){  //在线用户收到即时消息，不在线用户收到离线消息
        ISysUserService userService = applicationContext.getBean(ISysUserService.class);
        IOffLineMsgService offLineMsgService = applicationContext.getBean(IOffLineMsgService.class);
        //在线用户发送实时消息
        for (Session session : sessions.values())
        {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                // 处理发送消息时的异常
            }
        }
        Long sendUserId = null;
        Map<String, List<String>> params = cursession.getRequestParameterMap();
        List<String> funcTypes = params.get("userid");
        if (!funcTypes.isEmpty()) {
            String userId = funcTypes.get(0);
            sendUserId = Convert.toLong(userId);
        }

        //离线用户发送离线消息：保存到数据库中，下次登陆弹出
        List<SysUser> userList = userService.allUserList();
        for (SysUser user:userList) {
            if(sessions.containsKey(user.getUserId().toString())){ //用户若在线则忽略
                continue;
            }
            OffLineMsg offLineMsg = new OffLineMsg();
            offLineMsg.setSendUserId(sendUserId);
            offLineMsg.setRecUserId(user.getUserId());
            offLineMsg.setSendTime(new Date());
            offLineMsg.setTitle("");
            offLineMsg.setContext(message);
            offLineMsg.setRecStatus("未读");
            offLineMsgService.save(offLineMsg);
        }
    }
}
